<script setup lang="ts" name="BpmnScales">
import { storeToRefs } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import EventEmitter from '@/utils/EventEmitter'

const { scale } = storeToRefs(useModelerStore())
const canvas = ref(null)

const zoomReset = (newScale) => {
  const modeler = useModelerStore().getModeler
  const canvas = modeler.get('canvas')
  canvas.zoom(newScale, newScale === 'fit-viewport' ? 'auto' : { x: 0, y: 0 })
}

const zoomOut = (newScale) => {
  scale.value = Math.floor(scale.value * 100 - newScale * 100) / 100
  zoomReset(scale.value)
}

const zoomIn = (newScale) => {
  scale.value = Math.floor(scale.value * 100 + newScale * 100) / 100
  zoomReset(scale.value)
}

EventEmitter.on('modeler-init', (modeler) => {
  try {
    canvas.value = modeler.get('canvas')
    scale.value = canvas.value.zoom()
  } finally {
    modeler.on('canvas.viewbox.changed', ({ viewbox }) => {
      scale.value = viewbox.scale
    })
  }
})
</script>

<template>
  <div class="button-group">
    <el-tooltip effect="light" content="缩小视图" placement="bottom" :hide-after="100">
      <div class="item-button" @click="zoomOut(0.1)"><svg-icon icon="ri:zoom-out-line"></svg-icon></div>
    </el-tooltip>
    <el-tooltip effect="light" content="重置视图" placement="bottom" :hide-after="100">
      <div class="item-button input" @click="zoomReset('fit-viewport')">{{ Math.floor(scale * 10) * 10 + '%' }}</div>
    </el-tooltip>
    <el-tooltip effect="light" content="放大视图" placement="bottom" :hide-after="100">
      <div class="item-button" @click="zoomIn(0.1)"><svg-icon icon="ri:zoom-in-line"></svg-icon></div>
    </el-tooltip>
  </div>
</template>

<style scoped lang="scss">
.button-group {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 2px 2px 3px;
  border-right: 1px solid var(--el-border-color-lighter);

  .item-button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    margin: 2px;
    border-radius: 2px;
    cursor: pointer;

    &.input {
      width: 70px;
    }

    &.disabled {
      cursor: not-allowed;

      .el-icon {
        color: var(--el-text-color-disabled);
      }

      &:hover {
        background-color: transparent;

        .el-icon {
          color: var(--el-text-color-disabled);
        }
      }
    }

    &:hover {
      background-color: var(--el-color-primary-light-9);

      .el-icon {
        color: var(--el-color-primary);
      }
    }

    .el-icon {
      font-size: 20px !important;
    }
  }
}
</style>
